package com.zzh.service.impl;

import com.alibaba.fastjson.JSON;
import com.zzh.entity.Result;
import com.zzh.service.TwitterMonitorService;
import com.zzh.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author wenrouyue
 * @FileName: TwitterMonitorServiceImpl
 * @description
 * @create 2023/4/27-11:59
 **/
@Slf4j
@Service
public class TwitterMonitorServiceImpl implements TwitterMonitorService {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public Result<List<String>> searchMessage() {
        Set<String> apikey = redisTemplate.opsForSet().members("apikey");
        ArrayList<String> resList = new ArrayList<>();
        if (apikey != null && apikey.size() > 0) {
            log.info("获取apikey池数量:{}", apikey.size());
            List<Object> randomSet = getRandomSet(apikey);
            assert randomSet != null;
            String apiKey = (String) randomSet.get(1);
            String randNum = String.valueOf(randomSet.get(0));
            log.info("获取到apikey池中坐标:{}", randNum);
            assert apiKey != null;
            String[] s = apiKey.split("_");
            String oAuthConsumerKey = s[0];
            String oAuthConsumerSecret = s[1];
            String oAuthAccessToken = s[2];
            String oAuthAccessTokenSecret = s[3];
            ConfigurationBuilder cb = new ConfigurationBuilder();
            //todo linux服务代理得去掉
            cb.setDebugEnabled(true)
                    .setOAuthConsumerKey(oAuthConsumerKey)
                    .setOAuthConsumerSecret(oAuthConsumerSecret)
                    .setOAuthAccessToken(oAuthAccessToken)
                    .setOAuthAccessTokenSecret(oAuthAccessTokenSecret)
                    .setHttpProxyHost("127.0.0.1")
                    .setHttpProxyPort(10809);
            Twitter twitter = new TwitterFactory(cb.build()).getInstance();
            Paging paging = new Paging(1, 1);
            Set<String> twitterUserSet = redisTemplate.opsForSet().members("twitter_user");
            if (twitterUserSet != null && twitterUserSet.size() > 0) {
                log.info("获取twitter监控用户数量:{}", twitterUserSet.size());
                for (String user : twitterUserSet) {
                    try {
                        ResponseList<Status> statuses = twitter.getUserTimeline(user, paging);
                        for (Status status : statuses) {
                            log.info("status:{}", status);
                            String strTime = BianceAnnouncementImpl.toStrTime(Long.toString(status.getCreatedAt().getTime()));
                            String con = "来自于twitter的推文\n" +
                                    status.getUser().getName() + "发推时间: " + strTime + "\n" +
                                    "推文内容: " + status.getText();
                            resList.add(con);
                        }
                    } catch (TwitterException e) {
                        e.printStackTrace();
                    }
                }
            }
            return ResultUtil.getSuccess(resList);
        }
        resList.add("失败");
        return ResultUtil.getSuccess(resList);
    }

    public static long checkTime(String time1, String time2) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime1 = LocalDateTime.parse(time1, formatter);
        LocalDateTime dateTime2 = LocalDateTime.parse(time2, formatter);

        Duration duration = Duration.between(dateTime1, dateTime2);

        long seconds = duration.getSeconds();

        return seconds;
    }

    @Override
    public Result<String> addUser(String username) {
        log.info("正在新增监控用户:{}", username);
        Long twitterUser = redisTemplate.opsForSet().add("twitter_user", username);
        if (twitterUser != null) {
            return twitterUser > 0 ? ResultUtil.getSuccess("成功") : ResultUtil.getSuccess("失败");
        }
        return ResultUtil.getSuccess("异常");
    }

    @Override
    public Result<String> delUser(String username) {
        log.info("正在删除监控用户:{}", username);
        Long twitterUser = redisTemplate.opsForSet().remove("twitter_user", username);
        if (twitterUser != null) {
            return twitterUser > 0 ? ResultUtil.getSuccess("成功") : ResultUtil.getSuccess("失败");
        }
        return ResultUtil.getSuccess("异常");
    }

    /**
     * 从set集合中随机取出一个
     *
     * @param set 目标集合
     * @param <T> 泛型
     * @return index0 随机数 index1 obj
     */
    public static <T> List<Object> getRandomSet(Set<T> set) {
        int size = set.size();
        int item = new Random().nextInt(size);
        int i = 0;
        ArrayList<Object> ts = new ArrayList<>();
        ts.add(item);
        for (T obj : set) {
            if (i == item) {
                ts.add(obj);
                return ts;
            }
            i++;
        }
        return null;
    }

    private static final String USER_SCREEN_NAME = "BinanceUS"; // 指定要监控的用户的用户名
    private static final int MAX_TWEETS = 10; // 每次检查时要获取的最大推文数

    //    如果 BigDecimal 小于指定的 BigDecimal，则返回负整数。
//    如果 BigDecimal 等于指定的 BigDecimal，则返回零。
//    如果 BigDecimal 大于指定的 BigDecimal，则返回正整数。
    public static void main(String[] args) throws TwitterException {
//        long timestamp = Long.parseLong(timestampStr);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());

        String time1 = "2023-04-30 19:30:00";
        String time2 = sdf.format(date);
        BigDecimal num60 = new BigDecimal("60");
        long dividend = checkTime(time1,time2);
        long divisor = 60;
        System.out.println("time1:" + time1);
        System.out.println("time2:" + time2);
        System.out.println("dividend:" + dividend);
        BigDecimal quotient = BigDecimal.valueOf(dividend).divide(BigDecimal.valueOf(divisor), 2, BigDecimal.ROUND_HALF_UP);
        if (num60.compareTo(quotient) > 0) {
            System.out.println("num60 is greater than quotient");
        } else if (num60.compareTo(quotient) < 0) {
            System.out.println("num60 is less than quotient");
        } else {
            System.out.println("num60 is equal to quotient");
        }
    }

}
